package com.danielepelagatti.flickrmanager.model
{
	import mx.collections.ArrayCollection;
	import flash.utils.Dictionary;
	import com.adobe.webapis.flickr.Photo;
	import com.theriabook.utils.Logger;
	[Bindable]
	/**
	 * 
	 * @author dpelagatti
	 * 
	 */
	public class PhotoCollection extends ArrayCollection
	{
		/**
		 * 
		 * @param source
		 * 
		 */	
		public function PhotoCollection(source:Array=null):void
		{
			super(source);
		}
		/**
		 * 
		 * @param photo_id
		 * @return 
		 * 
		 */		
		public function getPhotoById(photo_id:String):Photo
		{
			for each(var photo:Photo in this)
			{
				if(photo.id == photo_id)return photo;
			}
			Logger.warn("PhotoCollection:: Requested photo_id: "+photo_id+"  does not exists");
			return null;
		}
		/**
		 * 
		 * @param photo_id
		 * 
		 */		
		public function removePhotoById(photo_id:String):Photo
		{
			for each(var photo:Photo in this)
			{
				if(photo.id == photo_id)
				{
					return removeItemAt(getItemIndex(photo)) as Photo;
				}
			}
			Logger.warn("PhotoCollection:: Tried to delete a non existing photo");
			return null;
		}
		/**
		 * 
		 * @param item
		 * @param index
		 * 
		 */		
		override public function addItemAt(item:Object, index:int):void
		{
			if(item is Photo)
			{
				if(Photo(item).id)
				{
					super.addItemAt(item,index);
				}
				else
					Logger.warn("PhotoCollection:: Tried to Add a photo with no id");
			}
			else
				Logger.warn("PhotoCollection:: Tried to add a non-Photo item");			
		}
		/**
		 * 
		 * @param item
		 * 
		 */
		override public function addItem(item:Object):void
		{
			if(item is Photo)
			{
				if(Photo(item).id)
				{
					var duplicate:Photo = getPhotoById(Photo(item).id);
					
					if(!duplicate)
						super.addItem(item);
					else
					{
						super.setItemAt(item,getItemIndex(duplicate));
						Logger.warn("PhotoCollection:: Avoided duplicate photo id ADD");
					}
				}
				else
					Logger.warn("PhotoCollection:: Tried to Add a photo with no id");
			}
			else
				Logger.warn("PhotoCollection:: tried to add a non-Photo item");
		}
		/**
		 * 
		 * @param index
		 * @return 
		 * 
		 */		
		override public function removeItemAt(index:int):Object
		{
			var removed:Photo = super.removeItemAt(index) as Photo;
			if(!removed)
				Logger.warn("PhotoCollection:: tried to remove a non existing photo");
			return removed;
		}
	}
}